package com.example.himg_rong.bofangqiapp;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import java.io.IOException;
import java.util.List;

public class PlayerActivity extends AppCompatActivity {
    private ImageView ivRet;
    private TextView tvMusicName;
    private TextView tvTitle;
    private TextView tvMusicLengthCurr;
    private TextView tvMusicLengthEnd;
    private SeekBar sbMusic;
    private ImageView ivXunhuan;
    private ImageView ivPlayAndStop;
    private ImageView ivShangYiShou;
    private ImageView ivXiaYiShou;

    private MediaPlayer mediaPlayer = new MediaPlayer();
    private Intent intent;
    private List<Music> musicList;
    private int curr;
    private Music music;
    private Boolean isPause = false;
    private Handler handler;
    private Boolean isDanqu = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        initView();
        intent = getIntent();
        musicList = (List<Music>) intent.getSerializableExtra("MusicList");
        curr = intent.getIntExtra("Curr",0);

        //返回
        ivRet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.reset();
                finish();
            }
        });

        player();

        //播放/暂停
        ivPlayAndStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPause){
                    player();
                }else {
                    ivPlayAndStop.setImageResource(R.drawable.play);
                    mediaPlayer.pause();
                    isPause = true;
                }
            }
        });

        //循环模式
        ivXunhuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isDanqu){
                    ivXunhuan.setImageResource(R.drawable.liebiaoxunhuan);
                    isDanqu = false;
                }else {
                    ivXunhuan.setImageResource(R.drawable.danquxunhuan);
                    isDanqu = true;
                }
            }
        });

        //上一首
        ivShangYiShou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curr==0){
                    curr=musicList.size()-1;
                }else {
                    curr--;
                }
                isPause = false;
                player();
            }
        });

        //下一首
        ivXiaYiShou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (curr==musicList.size()-1){
                    curr = 0;
                }else{
                    curr++;
                }
                isPause = false;
                player();
            }
        });

        sbMusic.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if(isDanqu){
                    player();
                }else {
                    if (curr==musicList.size()-1){
                        curr = 0;
                    }else{
                        curr++;
                    }
                    player();
                }

            }
        });
    }

    private String getMusicTime(int musicLength){
        musicLength = musicLength / 1000;
        int minute = musicLength / 60;
        int second = musicLength % 60;
        String minuteStr = minute<10 ? "0" + String.valueOf(minute):String.valueOf(minute);
        String secondStr = second<10 ? "0" + String.valueOf(second):String.valueOf(second);
        return minuteStr + ":" + secondStr;
    }

    private void player() {
        Log.e("curr:",String.valueOf(curr));
        ivPlayAndStop.setImageResource(R.drawable.stop);
        if (isPause){
            mediaPlayer.start();
            isPause = false;
        }else {
            try {
                mediaPlayer.reset();
                music = musicList.get(curr);
                tvMusicName.setText(music.getName());
                int index = music.getName().indexOf(".");
                tvTitle.setText(music.getName().substring(0,index));
                mediaPlayer.setDataSource(music.getUrl());
                mediaPlayer.prepare();
                mediaPlayer.start();
                tvMusicLengthEnd.setText(getMusicTime(mediaPlayer.getDuration()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            musicThread();
        }
    }

    private void musicThread() {
        //进度条
        sbMusic.setMax(mediaPlayer.getDuration());

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    if(mediaPlayer.isPlaying()){
                        int curr = mediaPlayer.getCurrentPosition();
                        int end = mediaPlayer.getDuration();
                        sbMusic.setProgress(curr);
                        Message message = new Message();
                        message.what = 1;
                        message.arg1 = curr;
                        handler.sendMessage(message);
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if(message.what == 1){
                    tvMusicLengthCurr.setText(getMusicTime(message.arg1));
                }
                return false;
            }
        });
    }

    private void initView() {
        ivRet = findViewById(R.id.iv_ret);
        tvMusicName = findViewById(R.id.tv_musicName);
        tvTitle = findViewById(R.id.tv_title);
        tvMusicLengthCurr = findViewById(R.id.tv_musicLengthCurr);
        tvMusicLengthEnd = findViewById(R.id.tv_musicLengthEnd);
        sbMusic = findViewById(R.id.sb_music);
        ivXunhuan = findViewById(R.id.iv_xunhuan);
        ivPlayAndStop = findViewById(R.id.iv_playAndStop);
        ivShangYiShou = findViewById(R.id.iv_shangyishou);
        ivXiaYiShou = findViewById(R.id.iv_xiayishou);
    }
}
